#include "precompiled.h"
#include "TextureLoader.h"
#include "Common.h"

namespace TextureLoader{


	GLboolean initialized=false;

	void Init(){
		if(!initialized)
			ilInit();

		initialized=true;
	}

	int LoadTextureFromFile(char const* path, Texture &texture_obj){
		if(!initialized)
			return MYEXIT_DEVIL_NOT_INITIALIZED;

		// OpenGL texture id.
		GLuint texID[1];

		// DevIL image ID
		ILuint imageId[1];

		// generate DevIL Image IDs 
		ilGenImages(1, imageId); // Generation of numTextures image names 

		// create and fill array with GL texture ids 
		glGenTextures(1, &texID[0]); // Texture name generation 


		ilBindImage(imageId[0]); // Binding of DevIL image name 
		std::string fileloc = path;	// Loading of image
		//wchar_t const *ctmp = char_to_wchart( fileloc.c_str());
		GLboolean success = ilLoadImage( fileloc.c_str() );

		if (success) // If no error occured: 
		{
			// Convert every colour component into
			//unsigned byte. If your image contains alpha channel you can replace IL_RGB with IL_RGBA 
			success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE); 
			if (!success)
			{
				// Error occured 
				printError("Error: ","Couldn't convert image");
				return MYEXIT_FAILED_CONVERTIMAGE;
			}
			glBindTexture(GL_TEXTURE_2D, texID[0]); // Binding of texture name 
			//redefine standard texture values
			// We will use linear interpolation for mag/min filters.
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

			glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
			glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );

			// Texture specification 
			glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_BPP), ilGetInteger(IL_IMAGE_WIDTH),
				ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), GL_UNSIGNED_BYTE,
				ilGetData()); 
		}
		else
		{
			// Error occured 
			printError("Error: ", ("Couldn't load Image: " + fileloc).c_str());
		}

		// Because we have already copied image data into texture data we can release memory used by image. 
		ilDeleteImages(1, imageId); 

		texture_obj.set_texID(texID[0]);
		//return success;
		return 1;
	}

}